﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Text.RegularExpressions;

namespace MvcShop.Extensions.Html
{
    public static class PagerHelperExtension
    {
        /// <summary> 
        /// 分页Pager显示 
        /// </summary> 
        /// <param name="html"> </param> 
        /// <param name="currentPageStr">标识当前页码的QueryStringKey </param> 
        /// <param name="pageSize">每页显示 </param> 
        /// <param name="totalCount">总数据量 </param> 
        /// <returns> </returns>
        public static string Pager(this HtmlHelper html, string currentPageStr, int pageSize, int totalCount)
        {
            var queryString = html.ViewContext.HttpContext.Request.QueryString;
            int currentPage = 1; //当前页 
            var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数 
            var dict = new System.Web.Routing.RouteValueDictionary(html.ViewContext.RouteData.Values);
            var output = new System.Text.StringBuilder();
            if (!string.IsNullOrEmpty(queryString[currentPageStr]))
            {
                //与相应的QueryString绑定
                foreach (string key in queryString.Keys)
                    if (queryString[key] != null && !string.IsNullOrEmpty(key))
                        dict[key] = queryString[key];
                int.TryParse(queryString[currentPageStr], out currentPage);
            }
            else
            {
                //获取 ～/Page/{page number} 的页号参数
                if (html.ViewContext.RouteData.Values[currentPageStr] != null)
                    int.TryParse(dict[currentPageStr].ToString(), out currentPage);

            }
            if (currentPage <= 0) currentPage = 1;
            if (totalPages > 1)
            {
                if (currentPage != 1)
                {
                    //处理首页连接 
                    dict[currentPageStr] = 1;
                    output.AppendFormat("{0} ", html.RouteLink("首页", dict));
                }
                if (currentPage > 1)
                {
                    //处理上一页的连接 
                    dict[currentPageStr] = currentPage - 1;
                    output.Append(html.RouteLink("上一页", dict));
                }
                else
                {
                    output.Append("上一页");
                }
                output.Append(" ");
                int currint = 5;
                for (int i = 0; i <= 10; i++)
                {
                    //一共最多显示10个页码，前面5个，后面5个 
                    if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
                        if (currint == i)
                        {
                            //当前页处理 
                            output.Append(string.Format("[{0}]", currentPage));
                        }
                        else
                        {
                            //一般页处理
                            dict[currentPageStr] = currentPage + i - currint;
                            output.Append(html.RouteLink((currentPage + i - currint).ToString(), dict));
                        }
                    output.Append(" ");
                }
                if (currentPage < totalPages)
                {
                    //处理下一页的链接
                    dict[currentPageStr] = currentPage + 1;
                    output.Append(html.RouteLink("下一页", dict));
                }
                else
                {
                    output.Append("下一页");
                }
                output.Append(" ");
                if (currentPage != totalPages)
                {
                    dict[currentPageStr] = totalPages;
                    output.Append(html.RouteLink("末页", dict));
                }
                output.Append(" ");
            }
            output.AppendFormat("当前第：{0} 页 / 总共： {1} 页", currentPage, totalPages);//这个统计加不加都行
            return output.ToString();
        }

        public static string Pager(this HtmlHelper html, IPagedList model, bool alwaysShow, bool showNumber)
        {
            string text = "<!--没有任何数据,所以不显示分页控件-->";
            bool show = model.TotalCount > 0 && alwaysShow || model.TotalCount > model.PageSize;
            if (show)
            {
                StringBuilder sb = new StringBuilder();
                var reqUrl = html.ViewContext.RequestContext.HttpContext.Request.Url.ToString();
                string link = "";
                if (reqUrl.IndexOf("page") >= 0)
                {
                    Regex re = new Regex(@"page=(\d+)", RegexOptions.IgnoreCase);
                    link = re.Replace(reqUrl, "page=%7Bpage%7D");
                }
                else if (reqUrl.IndexOf("?") < 0)
                {
                    link = reqUrl + "?page=%7Bpage%7D";
                }
                else
                {
                    link = reqUrl + "&page=%7Bpage%7D";
                }

                #region 生成四个按钮

                TagBuilder root = new TagBuilder("div");
                root.AddCssClass("pagerDRUPAL");

                TagBuilder fBtn = new TagBuilder("a");
                fBtn.AddCssClass("btn");
                //fBtn.MergeAttribute("style", "font-family:Webdings;");
                fBtn.InnerHtml = "首页";

                TagBuilder pBtn = new TagBuilder("a");
                pBtn.AddCssClass("btn");
                //pBtn.MergeAttribute("style", "font-family:Webdings;");
                pBtn.InnerHtml = "上页";

                TagBuilder nBtn = new TagBuilder("a");
                nBtn.AddCssClass("btn");
                //nBtn.MergeAttribute("style", "font-family:Webdings;");
                nBtn.InnerHtml = "下页";

                TagBuilder lBtn = new TagBuilder("a");
                lBtn.AddCssClass("btn");
                //lBtn.MergeAttribute("style", "font-family:Webdings;");
                lBtn.InnerHtml = "末页";

                #endregion

                int p = model.PageIndex;
                #region 判断首尾页
                if (model.IsPreviousPage)
                {
                    string pUrl = link.Replace("%7Bpage%7D", (p - 1).ToString());
                    string fUrl = link.Replace("%7Bpage%7D", (1).ToString());
                    fBtn.MergeAttribute("href", fUrl);
                    pBtn.MergeAttribute("href", pUrl);
                }
                else
                {
                    fBtn.MergeAttribute("disabled", "disabled");
                    pBtn.MergeAttribute("disabled", "disabled");
                }

                if (model.IsNextPage)
                {
                    string nUrl = link.Replace("%7Bpage%7D", (p + 1).ToString());
                    string lUrl = link.Replace("%7Bpage%7D", model.TotalPages.ToString());
                    nBtn.MergeAttribute("href", nUrl);
                    lBtn.MergeAttribute("href", lUrl);
                }
                else
                {
                    nBtn.MergeAttribute("disabled", "disabled");
                    lBtn.MergeAttribute("disabled", "disabled");
                }

                #endregion

                sb.Append(fBtn.ToString());
                sb.Append(pBtn.ToString());

                #region 生成中间数字
                if (showNumber)
                {
                    int begin = p - 5;
                    int end = p + 5;
                    if (begin < 1)
                    {
                        begin = 1;
                        end = 11;
                    }
                    if (end > model.TotalPages)
                    {
                        end = model.TotalPages;
                        begin = end > 11 ? end - 10 : 1;
                    }

                    for (int i = begin; i <= end; i++)
                    {
                        TagBuilder num = new TagBuilder("span");
                        if (p == i)
                        {
                            num.AddCssClass("current");
                            num.InnerHtml = i.ToString();
                        }
                        else
                        {
                            string url = link.Replace("%7Bpage%7D", i.ToString());
                            num.AddCssClass("num");
                            TagBuilder a = new TagBuilder("a");
                            a.MergeAttribute("href", url);
                            a.InnerHtml = i.ToString();
                            num.InnerHtml = a.ToString() + " ";
                        }
                        sb.Append(num.ToString());
                    }
                }
                #endregion

                sb.Append(nBtn.ToString());
                sb.Append(lBtn.ToString());

                #region 生成页信息
                TagBuilder index = new TagBuilder("span");
                index.AddCssClass("num");
                index.InnerHtml = p.ToString();

                TagBuilder pagecount = new TagBuilder("span");
                pagecount.AddCssClass("num");
                pagecount.InnerHtml = model.TotalPages.ToString();

                TagBuilder pagesize = new TagBuilder("span");
                pagesize.AddCssClass("num");
                pagesize.InnerHtml = model.PageSize.ToString();

                TagBuilder count = new TagBuilder("span");
                count.AddCssClass("num");
                count.InnerHtml = model.TotalCount.ToString();

                sb.Append(string.Format(" 第{0}页/共{1}页 每页{2}条记录 合计{3}条", index.ToString(), pagecount.ToString(), pagesize.ToString(), count.ToString()));

                root.InnerHtml = sb.ToString();
                text = root.ToString();

                #endregion
            }
            return text;
        }
    }
}
